package qj;

import java.awt.Component;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.text.DecimalFormat;
import java.text.NumberFormat;

import javax.swing.JFrame;
import javax.swing.JTextField;

import qj.tool.jna.JnaUtil;
import qj.tool.jna.KeyboardHandler;
import qj.util.DesktopUtil;
import qj.util.SwingUtil;
import qj.util.SwingUtil.RowAdder;
import qj.util.ThreadUtil;
import qj.util.appCommon.swing.AppFrame;
import qj.util.funct.F0;
import qj.util.funct.Fs;
import qj.util.funct.P0;
import qj.util.funct.P1;

public class AutoClick {
	// 41.2
	public static void main(String[] args) {
		AppFrame f = new AppFrame("Gunny");
		f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
		RowAdder rowAdder = SwingUtil.rowAdder(f);
		
		final JTextField forceTf = SwingUtil.tfPref("force", 20, "30");
		rowAdder.row("Luc ban", forceTf);
		rowAdder.whole(numberPanel(forceTf));
//		final JTextField rateTf = new JTextField("41.2");
//		rowAdder.row("Rate", rateTf);
		f.setVisible(true);
		
		KeyboardHandler.listenPressed(KeyboardHandler.DELETE, ThreadUtil.async1(new P1<F0<Boolean>>() {public void e(F0<Boolean> interrupted) {
			DesktopUtil.robot.keyPress(KeyEvent.VK_SPACE);
			System.out.println("Pressed");
			double force = Double.parseDouble(forceTf.getText().trim());
//			double rate = Double.parseDouble(rateTf.getText());
			double rate = 41.2;
			ThreadUtil.sleep((long)(force * rate));
			
			if (interrupted.e()) return;
			
			DesktopUtil.robot.keyRelease(KeyEvent.VK_SPACE);
			System.out.println("Released");
		}}));
	} 

	
	private static Component numberPanel(final JTextField tf) {
		final DecimalFormat NF = new DecimalFormat("##.##");
		return SwingUtil.panel(
				SwingUtil.btn("<", new P0() {public void e() {
					tf.setText(
							NF.format(Double.parseDouble(tf.getText()) - 1)
					);
				}}),
				SwingUtil.btn(">", new P0() {public void e() {
					tf.setText(
							NF.format(Double.parseDouble(tf.getText()) + 1)
					);
				}})
				);
	}

	private static void a1() {
		boolean[] active = new boolean[] {false};
		KeyboardHandler.listen(KeyboardHandler.LCTRL, Fs.update(active));
		
		while (true) {
			if (active[0]) {
				DesktopUtil.robot.mousePress(InputEvent.BUTTON1_MASK);
				ThreadUtil.sleep(10);
				DesktopUtil.robot.mouseRelease(InputEvent.BUTTON1_MASK);
				ThreadUtil.sleep(5);
			} else {
				ThreadUtil.sleep(60);
			}
		}
	}
}
